using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using HtmlAgilityPack;
using Newtonsoft.Json;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Text;

namespace html_table
{
    [Icon("pack://application:,,,/html_table;component/Resources/Icon.png")]
    [Designer("html_table.Designer.html_tableServerCommandDesigner, html_table")]
    public class html_tableServerCommand : Command, ICommandExecutableInServerSideAsync
    {
        [FormulaProperty]
        [DisplayName("html数据源")]
        public object AddNumber1 { get; set; }

        [ResultToProperty]
        [DisplayName("返回结果")]
        public string ResultTo { get; set; } = "返回结果";

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var add1 = await dataContext.EvaluateFormulaAsync(AddNumber1); // 计算的一个加数的公式值

            string ass1 = add1?.ToString() ?? string.Empty;//转换为字符串并判断是否空值

            //转换utf8
            byte[] utf8Bytes = Encoding.UTF8.GetBytes(ass1);
            string utf8String = Encoding.UTF8.GetString(utf8Bytes);

            // 使用 HtmlAgilityPack 解析 HTML
            var doc = new HtmlDocument();
            doc.LoadHtml(utf8String);


            // 找到表格元素
            var tables = doc.DocumentNode.SelectNodes("//table");
            // 用于存储表格数据的列表
            List<JObject> tableDataList = new List<JObject>();

            if (tables != null)
            {
                foreach (var table in tables)
                {
                    var headers = table.SelectNodes(".//th");
                    var rows = table.SelectNodes(".//tr");

                    if (headers != null && rows != null && rows.Count > 1)
                    {
                        JArray headerArray = new JArray();
                        foreach (var header in headers)
                        {
                            string headerText = header.InnerText.Trim().Replace("&nbsp;", "null"); // 将 &nbsp; 替换为空格
                            headerArray.Add(headerText);
                        }

                        for (int i = 1; i < rows.Count; i++)
                        {
                            var cells = rows[i].SelectNodes(".//td");
                            if (cells != null && cells.Count == headers.Count)
                            {
                                JObject rowObject = new JObject();
                                for (int j = 0; j < headers.Count; j++)
                                {
                                    rowObject[headerArray[j].ToString()] = cells[j].InnerText.Replace("&nbsp;", "null").Trim();
                                }
                                tableDataList.Add(rowObject);
                            }
                        }
                    }
                }

                // 将表格数据转换为JSON格式
                string json = JsonConvert.SerializeObject(tableDataList, Formatting.Indented);
                dataContext.Parameters[ResultTo] = json;  // 把计算的结果设置到结果变量中

                // 输出JSON格式的表格数据
                 Console.WriteLine(json);
            }
            else
            {
                dataContext.Parameters[ResultTo] = add1;  // 把计算的结果设置到结果变量中
            }

            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "提取html表格转json";
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }
    }
}
